<?php

class Logger {

	private static $_instances = array();
	private static $_last_instance;
	private $log_file;
	private $file_descr;
	private $unique_id;

	private $log_to_console;
	private $log_to_file;

	private $log_enabled = true;

	//===================================================================================

	function __construct($log_file) {
		$this->file_descr = null;
		$this->log_file = $log_file;
		$this->unique_id = Util::create_unique_id();

		$this->log_to_console = false;

		if (is_writeable($log_file)) {
			$dir_name = dirname($this->log_file);
			if (!is_dir($dir_name)) {
				mkdir ($dir_name, 0777, true);
			}

			$this->file_descr = fopen($this->log_file, "a+");
			$this->log_to_file = true;
		} else {
			$this->log_to_file = false;
		}
	}

	//===================================================================================

	function __destruct() {
		if ($this->file_descr) {
			fclose($this->file_descr);
			$this->file_descr = null;
		}
	}

	//===================================================================================

	public static function getInstance($log_file = null) {
		if ($log_file === null) {
			$log_file = self::$_last_instance;
		} else {
			self::$_last_instance = $log_file;
		}
		if (isset(self::$_instances[$log_file])) return self::$_instances[$log_file];
		return self::$_instances[$log_file] = new self($log_file);
	}

	//===================================================================================

	private function log_to_console($incomming_msg) {
		$messages = explode("\n", $incomming_msg);
		foreach ($messages as $message) {
			echo date("D M j G:i:s T Y").": ".$this->unique_id.": ".$message."\n";
		}
	}

	//===================================================================================

	/// Public functions

	public function turn_on_logging() {
		$this->log_enabled = true;
	}

	public function turn_off_logging() {
		$this->log_enabled = false;
	}

	public function set_log_to_console($flag) {
		$this->log_to_console = $flag;
	}

	public function set_log_to_file($flag) {
		$this->log_to_file = $flag;
	}

	public function log($incomming_msg) {
		if ($this->log_enabled == false)
			return;

		if ($this->log_to_console) {
			$this->log_to_console($incomming_msg);
		}

		if ($this->log_to_file) {
			if (!$this->file_descr)
				return;

			$messages = explode("\n", $incomming_msg);
			foreach ($messages as $message) {
				fwrite($this->file_descr, date("D M j G:i:s T Y").": ".$this->unique_id.": ".$message."\n");
			}
		}
	}
}

?>
